package com.mybatisplus.controller;

import com.mybatisplus.entity.QuartzJob;
import com.mybatisplus.job.QuartzManage;
import com.mybatisplus.mapper.QuartzJobMapper;
import com.mybatisplus.utils.ResponseEntityT;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @description：动态定时器
 * @modified By：
 * @version: 1.0$
 */
@Api(tags="动态定时器")
@RestController
@RequestMapping("/job")
public class JobController {

    @Autowired
    private QuartzJobMapper quartzJobMapper;

    @Autowired
    private QuartzManage quartzManage;

    /**
     * @return
     */
    @ApiOperation(value="定时器列表-列表查询", notes="定时器列表")
    @GetMapping(value = "/list")
    public ResponseEntityT<List<QuartzJob>> queryPageList() {
        return ResponseEntityT.OK(quartzJobMapper.getList());
    }

    /**
     *   添加
     * @param quartzJob
     * @return
     */
    @ApiOperation(value="添加", notes="添加")
    @PostMapping(value = "/add")
    public ResponseEntityT<?> add(@RequestBody QuartzJob quartzJob,HttpServletRequest req) {
        quartzJob.setIsPause(0);
        quartzJobMapper.insert(quartzJob);
        quartzManage.addJob(quartzJob);
        return ResponseEntityT.OK("添加成功！");
    }
    /**
     * 暂停/启动/删除
     * @param quartzJob
     * @return
     */
    @ApiOperation(value="暂停/启动/删除", notes="isPause = 1 暂停 2.立即启动 3.删除 0.恢复")
    @PutMapping(value = "/edit")
    public ResponseEntityT<?> edit(@RequestBody QuartzJob quartzJob) {
        QuartzJob findQuartzJob = quartzJobMapper.selectById(quartzJob.getId());
        if(quartzJob==null) {
            return ResponseEntityT.error("未找到对应数据");
        }
        if(quartzJob.getIsPause() == 0){
            quartzManage.resumeJob(findQuartzJob);
            findQuartzJob.setIsPause(0);
            quartzJobMapper.updateById(findQuartzJob);
        }
        if(quartzJob.getIsPause() == 1){
            quartzManage.pauseJob(findQuartzJob);
            findQuartzJob.setIsPause(1);
            quartzJobMapper.updateById(findQuartzJob);
        }
        if(quartzJob.getIsPause() == 2){
            quartzManage.runJobNow(findQuartzJob);
        }
        if(quartzJob.getIsPause() == 3){
            quartzManage.deleteJob(findQuartzJob);
            quartzJobMapper.deleteById(findQuartzJob);
        }
        return ResponseEntityT.OK("操作成功!");
    }

}
